/*
 * @version 1.0
 * @date 17-9-11 上午10:04
 * Copyright 杭州优谷数据技术有限公司   All Rights Reserved
 *  未经授权不得进行修改、复制、出售及商业使用
 */

package com.radioapp.liaoliaobao.view.sendcode;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.EditText;
import android.widget.Toast;

import com.jaydenxiao.common.base.BaseActivity;
import com.jaydenxiao.common.baserx.ApiException;
import com.jaydenxiao.common.baserx.RxHelper;
import com.jaydenxiao.common.baserx.RxSubscriber;
import com.jaydenxiao.common.manager.ServiceManager;
import com.radioapp.liaoliaobao.R;
import com.radioapp.liaoliaobao.api.UserService;
import com.radioapp.liaoliaobao.bean.enumbean.SendSmsUrlEnum;
import com.radioapp.liaoliaobao.utils.RegexUtil;

import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;

/**
 * 发送验证码TextView
 */
public class SendCodeTypeView extends AppCompatTextView {

    /**
     * 手机号.
     **/
    private String mPhoneStr;

    /**
     * 手机号对应的editText.
     **/
    private EditText mEtPhone;

    /**
     * 发送验证的类型
     */
    private String mType;
    /**
     * 倒计时完成监听
     **/
    private CountDownComplete mListener;

    private SendCodeListener mCodeListener;

    /**
     * 获取短信验证码
     **/
    private GetCodeListener mGetCodeListener;

    /**
     * 字体大小.
     **/
    private static final int TEXT_SIZE = 14;

    /**
     * 等待时间.
     **/
    private static final int WAIT_TIME = 60;
    private static final int SECOND = 1;

    private Activity activity;


    /**
     * Uri地址
     */
    private String url;

    private Disposable mdDisposable;

    public void setActivity(Activity activity){
        this.activity=activity;
    }

    public void setPhoneStr(String mPhoneStr) {
        this.mPhoneStr = mPhoneStr;
    }

    public void setEtPhone(EditText mEtPhone) {
        this.mEtPhone = mEtPhone;
    }

    public String getType() {
        return mType;
    }

    public void setType(String type) {
        mType = type;
    }

    public SendCodeTypeView(Context context) {
        super(context);
    }

    public SendCodeTypeView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setNormalState();
    }

    /**
     * 普通状态可点击.
     **/
    private void setNormalState() {
        setClickable(true);
        setText(getStrById(R.string.code_send_code));
        setEnabled(true);
      //  setTextSize(TEXT_SIZE);

        setOnClickListener(v -> onClickListener());
    }


    public void setUrl(String url) {
        this.url = url;
    }

    /**
     * 点击事件.
     **/
    private void onClickListener() {
        String phone;

        if (mEtPhone != null) {
            phone = mEtPhone.getText().toString();
        } else {
            phone = mPhoneStr;
        }

        if (mCodeListener != null) {
            mCodeListener.onclick();
        }

        if (checkPhone(phone)) requestSendCode(phone);
    }

    /**
     * 检查手机号.
     **/
    private boolean checkPhone(String phone) {
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(getContext(), getStrById(R.string.code_empty_phone_hint), Toast.LENGTH_SHORT).show();
            return false;
        }

        if (!RegexUtil.isMobile(phone)) {
            Toast.makeText(getContext(), getStrById(R.string.code_correct_phone_hint), Toast.LENGTH_SHORT).show();
            return false;
        }


        return true;
    }

    /**
     * 发送验证码.
     **/
    @SuppressWarnings("AccessStaticViaInstance")
    private void requestSendCode(String phone) {
        ServiceManager.create(UserService.class)
                .sendMobileSms(TextUtils.isEmpty(url) ? SendSmsUrlEnum.REGISTERSMSURL.getCode() : url, phone)
                .compose(RxHelper.handleFlatMap())
                .subscribe(new RxSubscriber<Object>(getContext(), false) {

                    @Override
                    protected void subscribe(Disposable d) {

                    }

                    @Override
                    protected void _onNext(Object o) {
                        setClickable(false);
                        requestSendCodeSuccess();
                        // ToastUitl.showLong(s.getvCode());
                        if (mGetCodeListener != null) {
                            mGetCodeListener.getCode();
                        }
                    }

                    @Override
                    protected void _TokenInvalid() {
                        if(activity instanceof BaseActivity) {
                            ((BaseActivity) activity).tokenInvalid();
                        }
                    }

                   /* @Override
                    protected void _onError(String message) {
                        super._onError(message);
                        setClickable(true);
                    }*/

                    @Override
                    protected void _onError(ApiException api) {
                        super._onError(api);
                        setClickable(true);
                    }
                });
    }

    /**
     * 发送验证码成功
     **/
    private void requestSendCodeSuccess() {
        setWaitState();
        //从0开始发射11个数字为：0-10依次输出，延时0s执行，每1s发射一次。
        mdDisposable = Flowable.intervalRange(0, WAIT_TIME, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        setText(getContext().getString(R.string.code_wait, WAIT_TIME - aLong + ""));
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        //倒计时完毕置为可点击状态
                        setNormalState();
                        if (mListener != null) mListener.onComplete();
                    }
                })
                .subscribe();

    }

    /**
     * 已发送等待60秒状态.
     **/
    private void setWaitState() {
        setEnabled(false);
    }

    private String getStrById(int strId) {
        return getContext().getString(strId);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mdDisposable != null) {
            mdDisposable.dispose();
        }
    }

    /**
     * 倒计时完成接口
     **/
    public interface CountDownComplete {
        void onComplete();
    }

    /**
     * 倒计时完成接口
     **/
    public interface SendCodeListener {
        void onclick();
    }

    public interface GetCodeListener {
        void getCode();
    }


    public void setOnCountDownCompleteListener(CountDownComplete listener) {
        mListener = listener;
    }

    public void setCodeListener(SendCodeListener codeListener) {
        mCodeListener = codeListener;
    }

    public void setGetCodeListener(GetCodeListener getCodeListener) {
        mGetCodeListener = getCodeListener;
    }
}
